import { reactive, ref } from 'vue'
import { validateUtils } from '@/utils/common'

/**
 * 表单处理的组合式函数
 */
export function useForm(initialData = {}) {
  const form = reactive({ ...initialData })
  const errors = reactive({})
  const isSubmitting = ref(false)

  // 重置表单
  const resetForm = () => {
    Object.keys(form).forEach(key => {
      form[key] = initialData[key] || ''
    })
    clearErrors()
  }

  // 清除错误
  const clearErrors = () => {
    Object.keys(errors).forEach(key => {
      delete errors[key]
    })
  }

  // 设置错误
  const setError = (field, message) => {
    errors[field] = message
  }

  // 验证字段
  const validateField = (field, value, rules = []) => {
    clearError(field)
    
    for (const rule of rules) {
      const result = rule(value)
      if (result !== true) {
        setError(field, result)
        return false
      }
    }
    return true
  }

  // 清除单个字段错误
  const clearError = (field) => {
    delete errors[field]
  }

  // 验证整个表单
  const validateForm = (rules = {}) => {
    clearErrors()
    let isValid = true

    Object.keys(rules).forEach(field => {
      const fieldRules = rules[field]
      const value = form[field]
      
      if (!validateField(field, value, fieldRules)) {
        isValid = false
      }
    })

    return isValid
  }

  // 提交表单
  const submitForm = async (submitFn, rules = {}) => {
    if (isSubmitting.value) return

    if (!validateForm(rules)) {
      return false
    }

    isSubmitting.value = true
    try {
      const result = await submitFn(form)
      return result
    } catch (error) {
      console.error('表单提交失败:', error)
      throw error
    } finally {
      isSubmitting.value = false
    }
  }

  return {
    form,
    errors,
    isSubmitting,
    resetForm,
    clearErrors,
    setError,
    clearError,
    validateField,
    validateForm,
    submitForm
  }
}

// 常用验证规则
export const formRules = {
  required: (message = '此字段为必填项') => (value) => {
    return value && value.toString().trim() ? true : message
  },
  
  minLength: (min, message) => (value) => {
    return value && value.length >= min ? true : message || `最少需要${min}个字符`
  },
  
  maxLength: (max, message) => (value) => {
    return !value || value.length <= max ? true : message || `最多允许${max}个字符`
  },
  
  phone: (message = '请输入正确的手机号') => (value) => {
    return !value || validateUtils.isPhone(value) ? true : message
  },
  
  email: (message = '请输入正确的邮箱地址') => (value) => {
    return !value || validateUtils.isEmail(value) ? true : message
  }
}